package com.example.carprofile;


import java.io.OutputStreamWriter;

import android.os.Bundle;
import android.app.Activity;

import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	ListView listView;
	Button createCar;
	String XML_CONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cars><car><carMake></carMake><carModel></carModel><fuelType></fuelType><carYear></carYear><carColor></carColor><engineHp></engineHp><engineCcm></engineCcm></car></cars>";
	static String myXML = "cars.xml";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		fileCreate();

		ParseXML parseXML = new ParseXML();
		String[] myCars = parseXML.giveCars(myXML);
		
		listView = (ListView) findViewById(R.id.listView1);
		if (myCars.length == 0 || myCars == null) 
				Toast.makeText(this, "Your car list is empty. Please create a new car!", Toast.LENGTH_LONG).show();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_view_row, R.id.textView1, myCars);
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				startActivity(new Intent(MainActivity.this, CarOptions.class));
			}
			});
		
		  createCar = (Button) findViewById(R.id.button1);
		  createCar.setOnClickListener(new OnClickListener() {
		  
		  @Override public void onClick(View v) { 
			  startActivity(new Intent(MainActivity.this, CarRegistration.class));
		  		  } 
		  });
		 
	}

	private void fileCreate() {

		try {
			OutputStreamWriter out = new OutputStreamWriter(openFileOutput(myXML, MODE_PRIVATE));
	        out.write(XML_CONTENT);
	        out.close();
	        Toast.makeText(MainActivity.this, "created", Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Toast.makeText(MainActivity.this, "NON created", Toast.LENGTH_LONG).show();
			Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
		}
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
